import {MenuService, SettingsService, TitleService} from '@delon/theme';
import {Component, Inject, OnDestroy, Optional} from '@angular/core';
import {Router} from '@angular/router';
import {FormBuilder, FormGroup, Validators} from '@angular/forms';
import {NzMessageService, NzNotificationService} from 'ng-zorro-antd';
import {DA_SERVICE_TOKEN, ITokenService, SocialOpenType, SocialService} from '@delon/auth';
import {ReuseTabService} from '@delon/abc';
import {environment} from '@env/environment';
import {Observable} from 'rxjs/Observable';
import {zip} from 'rxjs/observable/zip';
import 'rxjs/Rx';
import 'rxjs/add/operator/catch';
import {UtilityService} from '../../../service/utils.service';
import {Buffer} from 'buffer';
import {appConfig} from '../../../service/common';

@Component({
    selector: 'passport-login',
    templateUrl: './login.component.html',
    styleUrls: [ './login.component.less' ],
    providers: [ SocialService ]
})
export class UserLoginComponent implements OnDestroy {

    form: FormGroup;
    error = '';
    type = 0;
    loading = false;
    loginData: any; // 后台给的data属性

    constructor(
        fb: FormBuilder,
        private router: Router,
        public msg: NzMessageService,
        private settingsService: SettingsService,
        private socialService: SocialService,
        @Optional() @Inject(ReuseTabService) private reuseTabService: ReuseTabService,
        private nznot: NzNotificationService,
        private utilityService: UtilityService,
        private menuService: MenuService,
        @Inject(DA_SERVICE_TOKEN) private tokenService: ITokenService) {
        this.form = fb.group({
            userName: [null, [Validators.required, Validators.minLength(2)]],
            password: [null, Validators.required],
            mobile: [null, [Validators.required, Validators.pattern(/^1\d{10}$/)]],
            captcha: [null, [Validators.required]],
            remember: [true]
        });
    }

    // region: fields

    get userName() { return this.form.controls.userName; }
    get password() { return this.form.controls.password; }
    get mobile() { return this.form.controls.mobile; }
    get captcha() { return this.form.controls.captcha; }

    // endregion
    switch(ret: any) {
        this.type = ret.index;
    }

    // region: get captcha

    count = 0;
    interval$: any;

    getCaptcha() {
        this.count = 59;
        this.interval$ = setInterval(() => {
            this.count -= 1;
            if (this.count <= 0)
                clearInterval(this.interval$);
        }, 1000);
    }

    // endregion
    login(err) {
        if (err.code !== '200') {
            this.loading = false;
            if(!err.code){
                err.code = '网络异常，请稍后再试！';
            }
            this.nznot.create('error', err.code, err.msg);
        }
        return Observable.throw(err); /* 返回新的流接下去走 */
    }


    submit() {
        this.error = '';
        if (this.type === 0) {
            this.userName.markAsDirty();
            this.password.markAsDirty();
            if (this.userName.invalid || this.password.invalid) return;
        } else {
            this.mobile.markAsDirty();
            this.captcha.markAsDirty();
            if (this.mobile.invalid || this.captcha.invalid) return;
        }
        // mock http
        this.loading = true;
        const obj = {
            grant_type: 'password',
            username: this.userName.value,
            password : this.password.value
        };
        // let passBase = 'Basic ' + new Buffer(this.userName.value + ':' + this.password.value).toString('base64');
        // 加密客户端密码
        let passBase = 'Basic ' + new Buffer('APP01:123456').toString('base64');
        this.utilityService.postData(appConfig.loginUrl + '/' + appConfig.API.login + '?grant_type=password&username=' + this.userName.value + '&password=' + this.password.value, obj, {Authorization: passBase, 'Content-Type': 'application/x-www-form-urlencoded', Accept: 'application/json'})
            .catch(res => this.login(res))
            .mergeMap(loginData => {
                // 改成并行，把后台数据保存，同时去请求菜单，然后把请求的值带到下一个流
                let menuData;
                let funcList;
                this.loading = false;
                this.loginData = loginData; // 把后台给的值保存
                this.tokenService.set({
                    token: this.loginData.access_token,
                });
                 return this.utilityService.getData(appConfig.serverUrl + appConfig.VAPi.vgetMenu + this.userName.value + '/getMenu');
                // return   this.utilityService.getData('assets/app-data.json');
            })
            .subscribe(menu => { // 二次请求，请求菜单接口
                if (this.loginData.access_token) { // 如果存在，说明请求成功
                    this.reuseTabService.clear();
                    this.tokenService.set({
                        token: this.loginData.access_token,
                        name: menu.result.operator.operatorName,
                        userId: menu.result.operator.userId,
                        funcList: menu.result.permitBehave,
                        time: + new Date,
                        menu: menu.result
                    });
                    console.log(menu)
                    this.menuService.add(menu.result.menu); // 所有权限菜单
                    console.log('123')
                    // this.menuService.add(menu.menu); // 所有权限菜单
                    this.router.navigate(['/']);
                } else {
                    this.nznot.create('error', this.loginData.code, this.loginData.msg);
                }
            });
    }

    // region: social

    open(type: string, openType: SocialOpenType = 'href') {
        let url = ``;
        let callback = ``;
        if (environment.production)
            callback = 'https://cipchk.github.io/ng-alain/callback/' + type;
        else
            callback = 'http://localhost:4200/callback/' + type;
        switch (type) {
            case 'auth0':
                url = `//cipchk.auth0.com/login?client=8gcNydIDzGBYxzqV0Vm1CX_RXH-wsWo5&redirect_uri=${decodeURIComponent(callback)}`;
                break;
            case 'github':
                url = `//github.com/login/oauth/authorize?client_id=9d6baae4b04a23fcafa2&response_type=code&redirect_uri=${decodeURIComponent(callback)}`;
                break;
            case 'weibo':
                url = `https://api.weibo.com/oauth2/authorize?client_id=1239507802&response_type=code&redirect_uri=${decodeURIComponent(callback)}`;
                break;
        }
        if (openType === 'window') {
            this.socialService.login(url, '/', {
                type: 'window'
            }).subscribe(res => {
                if (res) {
                    this.settingsService.setUser(res);
                    this.router.navigateByUrl('/');
                }
            });
        } else {
            this.socialService.login(url, '/', {
                type: 'href'
            });
        }
    }

    // endregion

    ngOnDestroy(): void {
        if (this.interval$) clearInterval(this.interval$);
    }
}
